package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private SetmealMapper setmealMapper;


    /**
     * 新增菜品(包含口味)
     * @param dishDTO
     */
    @Transactional  //开启事务(当涉及到多张表的新增和修改时,需要开启事务)
    @Override
    public void saveWithFlavor(DishDTO dishDTO) {
        //0.开启事务
        //1.构造菜品数据,将菜品基本信息保存到dish表
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.insert(dish);

        //1.1 获取主键id值
        Long dishId = dish.getId();

        //2.构造口味数据,将口味信息保存到dish_flavor表
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            //2.1绑定菜品id
            flavors.forEach(flavor -> {
                flavor.setDishId(dishId);
            });
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 分页查询--使用分页插件
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        //1.设置分页参数
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());

        //2.调用mapper查询
        Page<DishVO> p = dishMapper.page(dishPageQueryDTO);

        //3.封装pageResult对象
        return new PageResult(p.getTotal(), p.getResult());
    }

    /**
     * 删除菜品
     * @param ids
     */
    @Transactional
    @Override
    public void delete(List<Long> ids) {
        //0.开启事务
        //1.调用mapper查询菜品数据(根据菜品id)
        List<Dish> dishes = dishMapper.getByIds(ids);

        //2.判断菜品是否启售,如果启售不允许删除
        dishes.forEach(dish -> {
            if (dish.getStatus().equals(StatusConstant.ENABLE)) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });

        //3.查询套餐菜品关系表, 根据菜品id去查
        Integer count = setmealDishMapper.countByDishId(ids);

        //4.判断是否被套餐关联,如果时则不允许删除
        if (count > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //5.删除菜品数据
        dishMapper.deleteBatch(ids);

        //6.删除口味数据
        dishFlavorMapper.deleteByDishIds(ids);

    }

    /**
     * 根据id查询菜品
     * @param id
     * @return
     */
    @Override
    public DishVO getById(Long id) {
        //1.查询出菜品基本信息,封装到DishVO中
        Dish dish = dishMapper.getById(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);

        //2.查询出菜品口味信息数据,封装到DishVO中
        List<DishFlavor> flavors = dishFlavorMapper.getByDishId(id);
        dishVO.setFlavors(flavors);

        //3.返回dishVO对象
        return dishVO;
    }

    /**
     * 修改菜品及口味信息
     * @param dishDTO
     */
    @Transactional
    @Override
    public void updateWithFlavor(DishDTO dishDTO) {
        //0.开启事务
        //1.构造一个dish对象
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        //2.调用dishMapper,修改菜品基本信息
        dishMapper.update(dish);

        //3.获取口味信息,修改菜品相关的口味信息
        List<DishFlavor> flavors = dishDTO.getFlavors();
        //3.1 先删除原来的口味信息---关于口味信息: 可能是新增\ 修改\ 删除
        dishFlavorMapper.deleteByDishId(dishDTO.getId());   //逻辑删除

        //3.2 再构造新的口味信息--绑定菜品id
        if (flavors != null && flavors.size() > 0) {
            //3.3绑定菜品id
            flavors.forEach(flavor -> {
                flavor.setId(null); //如果用的时逻辑删除,一定要记得把id置空,否则报主键id重复
                flavor.setDishId(dishDTO.getId());
            });
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 菜品起售、停售
     * @param status
     * @param id
     */
    @Transactional
    @Override
    public void enableOrDisable(Integer status, Long id) {
        //1.启售|停售菜品
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.update(dish);
        //2.如果是停售，需要将关联了该菜品的套餐也停售 需要先联表setmel_dish  setmeal dish查询得到套餐表
        if (status.equals(StatusConstant.DISABLE)) {
            Setmeal setmeal = setmealMapper.getByDishId(id);
            if (setmeal != null){   //有关联的套餐才需要更新
                setmeal.setStatus(status);
                setmealMapper.update(setmeal);
            }
        }
    }

    /**
     * 根据分类id查询菜品列表
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> getByCategoryId(Long categoryId, String name) {
        return dishMapper.getByCategoryId(categoryId, name);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
